package com.foosun.util.wechat;

import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.foosun.entity.wechat.RespCode;
import com.foosun.service.exception.WechatRuntimeException;
import com.foosun.util.https.HttpClientConnectionManager;

/**
 * 得到用户信息
 * @author hj
 * @date 2014-01-22
 */
public class WxUserUtil {
	
	// http客户端  
    public static DefaultHttpClient httpclient;  
      
    static {  
        httpclient = new DefaultHttpClient();  
        httpclient = (DefaultHttpClient) HttpClientConnectionManager.getSSLInstance(httpclient); // 接受任何证书的浏览器客户端  
    }
    
    
    public static void main(String[] args) {  
        try {  
            // 获取accessToken -参数appid，secret  
        	String accessToken = WxCommonUtils.getAccessToken("wx6eb63384bd102d9c");  
            System.out.println(accessToken);  
            /*String userinfo = getFollowList(accessToken);
            System.out.println(userinfo);*/
            /*String user = getUserInfo("b04uRRTk7monnPlteN-Qz7EapBncZlKlpNaCn8fLlamC5iuuWOJoiFCZjaRYdDDjwYXDTANmGeUS0Fzc2BciyA","owJNEuAN-ODJ_C8RLUan1dqUONKM");
            Map m = MessageUtil.parseUserinfo(user);
            
            System.out.println(m.get("nickname"));*/
            /*String t = getAllGroup(accessToken);
            System.out.println(t);*/
            //String user4 = getUserInfo("ecv2Xy0SYw65w5wSRVUmoYmw9E8iEDLCYLFOgJWGaXs6PRyWv3COHr8tRffKEIT6Ied6cVNxTLawd8vwm9H-ow","owJNEuNZz5VjunCb6MgITIShWn9Y");
            //System.out.println("user4="+user4);
            String tmp = "{\"touser\":\"owJNEuJKNx43vrYXfhhskSF_8bzA\","
        		    + "\"msgtype\":\"text\","
        		    +"\"text\": { \"content\": \"测试客服消息接口！\"} "
        		    +"}";
            
            String res = customerMessage(tmp,accessToken);
            System.out.println(res);
            /*long time = 1403078327569L;
            System.out.println(Long.parseLong(String.valueOf(time).substring(0,10)));*/
        } catch (Exception e) {  
            e.printStackTrace();  
        }  
    }
    
    /**
     * 获取关注者列表
     */
	public static String getFollowList(String accessToken) throws Exception { 
        HttpGet get = HttpClientConnectionManager.getGetMethod("https://api.weixin.qq.com/cgi-bin/user/get?access_token=" + accessToken);  
        HttpResponse response = httpclient.execute(get);  
        String jsonStr = EntityUtils.toString(response.getEntity(), "utf-8");  
        JSONObject object = JSON.parseObject(jsonStr); 
        String code = object.getString("errcode");
        if(code != null && (RespCode.APPSECRET_ERROR.getCode().equals(code) || RespCode.BUSY.getCode().equals(code) || RespCode.EXCEPTION_CATCHED.getCode().equals(code))){
        	throw new WechatRuntimeException(Integer.parseInt(code));
        }
        return jsonStr;  
    } 
	
	/**
     * 获取用户基本信息
     */
	public static String getUserInfo(String accessToken,String openid) throws Exception { 
        HttpGet get = HttpClientConnectionManager.getGetMethod("https://api.weixin.qq.com/cgi-bin/user/info?access_token=" + accessToken+"&openid="+openid+"&lang=zh_CN");  
        HttpResponse response = httpclient.execute(get);  
        String jsonStr = EntityUtils.toString(response.getEntity(), "utf-8");  
        JSONObject object = JSON.parseObject(jsonStr); 
        String code = object.getString("errcode");
        if(code != null && (RespCode.APPSECRET_ERROR.getCode().equals(code) || RespCode.BUSY.getCode().equals(code) || RespCode.EXCEPTION_CATCHED.getCode().equals(code))){
        	throw new WechatRuntimeException(Integer.parseInt(code));
        }
        return jsonStr;  
    }
    
    /**
     * 群发消息(用户openid列表发送)
     */
    public static String sendMessage(String params,String accessToken) throws Exception {    
        HttpPost post = HttpClientConnectionManager.getPostMethod("https://api.weixin.qq.com/cgi-bin/message/mass/send?access_token="+accessToken);
        post.setEntity(new StringEntity(params, "UTF-8")); 
        HttpResponse response = httpclient.execute(post);  
        String jsonStr = EntityUtils.toString(response.getEntity(), "utf-8");  
        System.out.println(jsonStr);  
        JSONObject object = JSON.parseObject(jsonStr); 
        String code = object.getString("errcode");
        if(code != null && (RespCode.APPSECRET_ERROR.getCode().equals(code) || RespCode.BUSY.getCode().equals(code) || RespCode.EXCEPTION_CATCHED.getCode().equals(code))){
        	throw new WechatRuntimeException(Integer.parseInt(code));
        }
        return object.getString("errmsg");

    }
    
    /**
     * 客服消息(用户openid列表发送)
     */
    public static String customerMessage(String params,String accessToken) throws Exception {    
        HttpPost post = HttpClientConnectionManager.getPostMethod("https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token="+accessToken);
        post.setEntity(new StringEntity(params, "UTF-8")); 
        HttpResponse response = httpclient.execute(post);  
        String jsonStr = EntityUtils.toString(response.getEntity(), "utf-8");  
        System.out.println(jsonStr);  
        JSONObject object = JSON.parseObject(jsonStr); 
        String code = object.getString("errcode");
        if(code != null && (RespCode.APPSECRET_ERROR.getCode().equals(code) || RespCode.BUSY.getCode().equals(code) || RespCode.EXCEPTION_CATCHED.getCode().equals(code))){
        	throw new WechatRuntimeException(Integer.parseInt(code));
        }  
        return object.getString("errmsg");

    }
    
    /**
     * 获取所有分组
     */
	public static String getAllGroup(String accessToken) throws Exception { 
        HttpGet get = HttpClientConnectionManager.getGetMethod("https://api.weixin.qq.com/cgi-bin/groups/get?access_token=" + accessToken);  
        HttpResponse response = httpclient.execute(get);  
        String jsonStr = EntityUtils.toString(response.getEntity(), "utf-8");  
        JSONObject object = JSON.parseObject(jsonStr); 
        String code = object.getString("errcode");
        if(code != null && (RespCode.APPSECRET_ERROR.getCode().equals(code) || RespCode.BUSY.getCode().equals(code) || RespCode.EXCEPTION_CATCHED.getCode().equals(code))){
        	throw new WechatRuntimeException(Integer.parseInt(code));
        }
        return jsonStr;  
    }
	
	/**
	 * 获取用户所在分组
	 * @param accessToken
	 * @param openid
	 * @return
	 * @throws Exception
	 */
	public static String getUserGroup(String accessToken,String openid) throws Exception { 
        HttpPost post = HttpClientConnectionManager.getPostMethod("https://api.weixin.qq.com/cgi-bin/groups/getid?access_token="+accessToken);
        String params = "{\"openid\":\""+openid+"\"}";
        post.setEntity(new StringEntity(params, "UTF-8")); 
        HttpResponse response = httpclient.execute(post);  
        String jsonStr = EntityUtils.toString(response.getEntity(), "utf-8");   
        JSONObject object = JSON.parseObject(jsonStr);  
        String code = object.getString("errcode");
        if(code != null && (RespCode.APPSECRET_ERROR.getCode().equals(code) || RespCode.BUSY.getCode().equals(code) || RespCode.EXCEPTION_CATCHED.getCode().equals(code))){
        	throw new WechatRuntimeException(Integer.parseInt(code));
        }
        return object.getString("groupid");
    }
}
